<template>
  <div class="table-box">
    <!-- 搜索表单 -->
    <el-form :model="searchForm" ref="searchFormRef" :inline="true" class="search-form">
      <el-form-item label="工单编码" prop="workOrderCode">
        <el-input v-model="searchForm.workOrderCode" placeholder="请输入工单编码" clearable />
      </el-form-item>
      <el-form-item label="产品型号" prop="productModel">
        <el-input v-model="searchForm.productModel" placeholder="请输入产品型号" clearable />
      </el-form-item>
      <el-form-item label="工单状态" prop="status">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 180px;">
          <el-option label="初始化" value="initialized" />
          <el-option label="准备完成" value="ready" />
          <el-option label="已下达" value="released" />
          <el-option label="生产中" value="started" />
          <el-option label="已暂停" value="suspended" />
          <el-option label="已完成" value="completed" />
          <el-option label="已关闭" value="closed" />
          <el-option label="已取消" value="cancelled" />
        </el-select>
      </el-form-item>
      <el-form-item label="工单类型" prop="workOrderType">
        <el-select v-model="searchForm.workOrderType" placeholder="请选择类型" clearable style="width: 180px;">
          <el-option label="标准生产工单" value="production" />
          <el-option label="返工工单" value="rework" />
          <el-option label="试产工单" value="trial" />
          <el-option label="外协工单" value="outsourcing" />
          <el-option label="维修工单" value="maintenance" />
          <el-option label="样品工单" value="sample" />
          <el-option label="工程变更工单" value="engineering_change" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-header">
      <el-button type="primary" :icon="CirclePlus" @click="handleAdd">新增工单</el-button>
      <el-button type="danger" :icon="Delete" plain :disabled="selectedRows.length === 0" @click="handleBatchDelete">
        批量删除
      </el-button>
    </div>
    
    <el-table 
      :data="tableData" 
      style="width: 100%" 
      v-loading="loading"
      @selection-change="handleSelectionChange"
      border 
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="workOrderCode" label="工单编码" />
      <el-table-column prop="workOrderType" label="工单类型" width="120">
        <template #default="scope">
          <el-tag :type="getWorkOrderTypeTagType(scope.row.workOrderType)" size="small">
            {{ getWorkOrderTypeText(scope.row.workOrderType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="productName" label="产品名称" />
      <el-table-column prop="routeName" label="工艺路线名称" />
      <el-table-column prop="productionLineName" label="产线名称" />

      <el-table-column prop="plannedQuantity" label="计划数量" />
      <el-table-column prop="completedQuantity" label="完成数量" />
      <el-table-column prop="status" label="工单状态">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="createdTime" label="创建时间" /> -->
      <el-table-column prop="plannedStartTime" label="计划开始时间" />
      <el-table-column prop="plannedEndTime" label="计划结束时间" />

      <el-table-column label="操作" width="400" fixed="right">
        <template #default="scope">
          <el-button type="primary" link :icon="View" @click="handleView(scope.row)" class="operation-btn">查看</el-button>
          <el-button type="primary" link :icon="EditPen" @click="handleEdit(scope.row)" class="operation-btn">编辑</el-button>
          
          <!-- 根据状态显示不同操作按钮 -->
          <el-button v-if="['initialized', 'ready'].includes(scope.row.status)" type="success" link @click="handleRelease(scope.row)" class="operation-btn">下达</el-button>
          <el-button v-if="scope.row.status === 'released'" type="warning" link @click="handleStart(scope.row)" class="operation-btn">开始</el-button>
          <el-button v-if="scope.row.status === 'started'" type="warning" link @click="handleSuspend(scope.row)" class="operation-btn">暂停</el-button>
          <el-button v-if="scope.row.status === 'suspended'" type="success" link @click="handleResume(scope.row)" class="operation-btn">恢复</el-button>
          <el-button v-if="scope.row.status === 'started'" type="success" link @click="handleComplete(scope.row)" class="operation-btn">完成</el-button>
          <el-button v-if="scope.row.status === 'completed'" type="info" link @click="handleClose(scope.row)" class="operation-btn">关闭</el-button>
          <el-button v-if="['initialized', 'ready', 'released'].includes(scope.row.status)" type="danger" link @click="handleCancel(scope.row)" class="operation-btn">取消</el-button>
          <el-button v-if="['initialized', 'ready', 'cancelled', 'closed'].includes(scope.row.status)" type="danger" link @click="handleDelete(scope.row)" class="operation-btn">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>
    
    <!-- 工单表单抽屉 -->
    <WorkOrderForm ref="formDrawerRef" />
  </div>
</template>

<script setup lang="ts" name="workOrderTable">
import { ref, reactive, onMounted } from "vue";
import type { FormInstance } from 'element-plus';
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlus, Delete, EditPen, View } from "@element-plus/icons-vue";
import WorkOrderForm from "./form.vue";
import { PageHelper } from "@/utils/pageHelper";
import {
  getWorkOrderList,
  releaseWorkOrder,
  startWorkOrder,
  suspendWorkOrder,
  resumeWorkOrder,
  completeWorkOrder,
  closeWorkOrder,
  cancelWorkOrder,
  updateWorkOrder,
  deleteWorkOrder,
  batchDeleteWorkOrder,
  type WorkOrder
} from "@/api/modules/workorder";
const loading = ref(false);
const tableData = ref<WorkOrder.WorkOrderListItem[]>([]);
const searchFormRef = ref<FormInstance>();
const selectedRows = ref<WorkOrder.WorkOrderListItem[]>([]);

// 查询表单
const searchForm = reactive({
  workOrderCode: '',
  productModel: '',
  status: '',
  workOrderType: ''
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'initialized': 'info',
    'ready': 'success',
    'released': 'warning',
    'started': 'primary',
    'suspended': 'warning',
    'completed': 'success',
    'closed': 'info',
    'cancelled': 'danger'
  };
  return statusMap[status] || 'info';
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'initialized': '初始化',
    'ready': '准备完成',
    'released': '已下达',
    'started': '生产中',
    'suspended': '已暂停',
    'completed': '已完成',
    'closed': '已关闭',
    'cancelled': '已取消'
  };
  return statusMap[status] || status;
};

// 获取工单类型标签类型
const getWorkOrderTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    'production': 'primary',
    'rework': 'warning',
    'trial': 'info',
    'outsourcing': 'success',
    'maintenance': 'danger',
    'sample': 'info',
    'engineering_change': 'warning'
  };
  return typeMap[type] || 'info';
};

// 获取工单类型文本
const getWorkOrderTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    'production': '生产',
    'rework': '返工',
    'trial': '试产',
    'outsourcing': '外协',
    'maintenance': '维修',
    'sample': '样品',
    'engineering_change': '工程变更'
  };
  return typeMap[type] || type;
};

// 获取表格数据
const getTableData = async () => {
  loading.value = true;
  try {
    const params = PageHelper.createPageParams(
      pagination.currentPage,
      pagination.pageSize,
      searchForm
    );
    const res = await getWorkOrderList(params);
    
    // 使用PageHelper安全解析分页数据
    const pageData = PageHelper.parsePage<WorkOrder.WorkOrderListItem>(res.data);
    tableData.value = pageData.records;
    pagination.total = pageData.total;
    
    console.log("解析后的分页数据:", pageData);
  } catch (error) {
    console.error('获取工单列表失败:', error);
    ElMessage.error('获取工单列表失败');
  } finally {
    loading.value = false;
  }
};

// 表格选择项变化
const handleSelectionChange = (rows: WorkOrder.WorkOrderListItem[]) => {
  selectedRows.value = rows;
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) return;
  
  ElMessageBox.confirm(
    `确认删除选中的 ${selectedRows.value.length} 条数据吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const ids = selectedRows.value.map(row => row.id);
      await batchDeleteWorkOrder(ids);
      ElMessage.success('批量删除成功');
      selectedRows.value = [];
      getTableData();
    } catch (error) {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除失败');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 查询
const handleSearch = () => {
  pagination.currentPage = 1;
  getTableData();
};

// 重置
const handleReset = () => {
  if (!searchFormRef.value) return;
  searchFormRef.value.resetFields();
  pagination.currentPage = 1;
  getTableData();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  getTableData();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  getTableData();
};

// 工单表单抽屉引用
const formDrawerRef = ref<InstanceType<typeof WorkOrderForm>>();

// 新增工单
const handleAdd = () => {
  const params = {
    title: "新增",
    isView: false,
    row: {},
    getTableList: getTableData
  };
  formDrawerRef.value?.open(params);
};

// 查看工单
const handleView = (row: WorkOrder.WorkOrderListItem) => {
  const params = {
    title: "查看",
    isView: true,
    row: { ...row },
    getTableList: getTableData
  };
  formDrawerRef.value?.open(params);
};

// 编辑工单
const handleEdit = (row: WorkOrder.WorkOrderListItem) => {
  const params = {
    title: "编辑",
    isView: false,
    row: { ...row },
    getTableList: getTableData
  };
  formDrawerRef.value?.open(params);
};

// 下达工单
const handleRelease = async (row: WorkOrder.WorkOrderListItem) => {
  try {
    await releaseWorkOrder(row.id);
    ElMessage.success('工单下达成功');
    getTableData();
  } catch (error) {
    console.error('工单下达失败:', error);
    ElMessage.error('工单下达失败');
  }
};

// 开始工单
const handleStart = async (row: WorkOrder.WorkOrderListItem) => {
  try {
    await startWorkOrder(row.id);
    ElMessage.success('工单开始成功');
    getTableData();
  } catch (error) {
    console.error('工单开始失败:', error);
    ElMessage.error('工单开始失败');
  }
};

// 暂停工单
const handleSuspend = async (row: WorkOrder.WorkOrderListItem) => {
  try {
    const { value: reason } = await ElMessageBox.prompt('请输入暂停原因', '暂停工单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '暂停原因不能为空'
    });
    
    await suspendWorkOrder(row.id, { suspendReason: reason });
    ElMessage.success('工单暂停成功');
    getTableData();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('工单暂停失败:', error);
      ElMessage.error('工单暂停失败');
    }
  }
};

// 恢复工单
const handleResume = async (row: WorkOrder.WorkOrderListItem) => {
  try {
    await resumeWorkOrder(row.id);
    ElMessage.success('工单恢复成功');
    getTableData();
  } catch (error) {
    console.error('工单恢复失败:', error);
    ElMessage.error('工单恢复失败');
  }
};

// 完成工单
const handleComplete = async (row: WorkOrder.WorkOrderListItem) => {
  try {
    const { value: quantity } = await ElMessageBox.prompt(
      `计划数量：${row.plannedQuantity}，请输入完成数量`, 
      '完成工单', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d+$/,
        inputErrorMessage: '请输入有效的数量'
      }
    );
    
    await completeWorkOrder(row.id, { completedQuantity: parseInt(quantity) });
    ElMessage.success('工单完成成功');
    getTableData();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('工单完成失败:', error);
      ElMessage.error('工单完成失败');
    }
  }
};

// 关闭工单
const handleClose = async (row: WorkOrder.WorkOrderListItem) => {
  try {
    const { value: reason } = await ElMessageBox.prompt('请输入关闭原因', '关闭工单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '关闭原因不能为空'
    });
    
    await closeWorkOrder(row.id, { closeReason: reason });
    ElMessage.success('工单关闭成功');
    getTableData();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('工单关闭失败:', error);
      ElMessage.error('工单关闭失败');
    }
  }
};

// 取消工单
const handleCancel = async (row: WorkOrder.WorkOrderListItem) => {
  try {
    const { value: reason } = await ElMessageBox.prompt('请输入取消原因', '取消工单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '取消原因不能为空'
    });
    
    await cancelWorkOrder(row.id, { cancelReason: reason });
    ElMessage.success('工单取消成功');
    getTableData();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('工单取消失败:', error);
      ElMessage.error('工单取消失败');
    }
  }
};

// 删除工单
const handleDelete = async (row: WorkOrder.WorkOrderListItem) => {
  ElMessageBox.confirm(
    `确认删除工单 "${row.workOrderCode}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await deleteWorkOrder(row.id);
      ElMessage.success('工单删除成功');
      getTableData();
    } catch (error) {
      console.error('工单删除失败:', error);
      ElMessage.error('工单删除失败');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 页面加载时获取数据
onMounted(() => {
  getTableData();
});
</script>

<style scoped>
.search-form {
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.table-header {
  margin-bottom: 16px;
  display: flex;
  gap: 10px;
}

.el-table {
  flex: 1;
}

:deep(.el-table__row) {
  height: 30px !important;
  line-height: 35px;
}

:deep(.el-table__cell) {
  padding: 12px 0;
}

:deep(.el-table__header-row) {
  height: 65px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}

:deep(.operation-btn) {
  font-size: 14px;
  margin: 0 2px;
}

:deep(.operation-btn .el-icon) {
  font-size: 16px;
  margin-right: 2px;
}
</style>